﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LGSVR.Common;
using LGSVR.BLL.Sys;
using System.Data;


namespace LGSVR_WEB.sys
{
    public partial class UserInfoEdit : DataBasePage
    {
        private int Pid
        {
            get
            {
                return string.IsNullOrEmpty(Request.QueryString["ID"]) ? 0 : int.Parse(Request.QueryString["ID"]);
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserID"] == null)
            {
                Page.ClientScript.RegisterStartupScript(this.GetType(), "out", "<script>alert('系统超时或服务器故障，请退出重新登录！');window.parent.parent.navigate('../Logout.aspx');</script>");
            }
            if (!IsPostBack)
            {
                AddAttributes();
                PageInit();

            }
        }

        private void AddAttributes()
        {
            //绑定ParentID
            bool isSupperAdmin = Session["ActName"].ToString() == "超级管理员";
            txtRX.Attributes.Add("onkeyup", "IsNumeric(this)");
            txtTX.Attributes.Add("onkeyup", "IsNumeric(this)");





            DataTable dtCompany = new CompanyBLL().GetCompanyList("");

            if (!isSupperAdmin)
            {
                var newcompany = from c in dtCompany.AsEnumerable()
                                 where c.Field<string>("companyID") == Session["CompanyID"].ToString()
                                 select new ListItem
                                 {
                                     Text = c.Field<string>("companyName"),
                                     Value = c.Field<string>("companyID")
                                 };
                dropcompanyID.Items.AddRange(newcompany.ToArray());
            }
            else
            {
                dropcompanyID.DataSource = dtCompany;
                dropcompanyID.DataTextField = "companyName";
                dropcompanyID.DataValueField = "companyID";
                dropcompanyID.DataBind();
            }


            dropcompanyID.Items.Insert(0, new ListItem("-请选择-", "0"));



            if (Session["ActName"].ToString() == "操作员")
            {
                dropactID.Items.Add(new ListItem("操作员", "操作员"));
                    
                dropactID.Enabled = false;
            }
            else
            {
                string strWhere = isSupperAdmin ? "" : " and ActName<>'超级管理员'";
                DataTable dtRole = GetListByTable("userAct", "state=1" + strWhere);
                dropactID.DataSource = dtRole;
                dropactID.DataTextField = "ActName";
                dropactID.DataValueField = "ActID";
                dropactID.DataBind();
            }
        }

        private void PageInit()
        {


            Dictionary<string, string> dicSingle;

            // 编辑
            if (!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"].ToLower() == "edit")
            {
                btnSave.Text = "更 新";
                if (Pid != 0)
                {
                    dicSingle = GetSigle("userInfo", "ID=" + Request.QueryString["ID"]);                   
                }
                else //主页面修改个人信息
                {
                    dicSingle = GetSigle("userInfo", "userid='" + Session["UserID"]+"' and state <>'P'");
                }
                if (dicSingle != null)
                {
                    txtcontent.Text = dicSingle["content"];
                    txtuserID.Text = dicSingle["userID"];
                    txtuserName.Text = dicSingle["userName"];
                    dropcompanyID.SelectedValue = dicSingle["companyID"];
                    txtPWD.Attributes.Add("value", dicSingle["PWD"]);
                    txtPortID.Text = dicSingle["PortID"];
                   
                    dropactID.SelectedValue = dicSingle["actID"];
                    
                    txtRX.Text = dicSingle["RX"];
                    txtTX.Text = dicSingle["TX"];
                   
                    txtcontent.Text = dicSingle["content"];
                    hidPwd.Value = dicSingle["PWD"];


                }
                else
                {
                    MsgContent = ShowMessage("数据加载失败。", MessageType.Error, true, false);
                }
            }
            //else
            //{
            //    txtPWD.Attributes.Add("");
            //}
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> dicParam;

            dicParam = new Dictionary<string, string>();

            dicParam.Add("userID", txtuserID.Text.Trim());
            dicParam.Add("userName", txtuserName.Text.Trim());
            dicParam.Add("companyID", dropcompanyID.SelectedValue);
            //if (Pid == 0)
            //{
            //    dicParam.Add("PWD", System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPWD.Text.Trim(), "SHA1"));
            //}
            //else
            //{
            string newPwd =System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPWD.Text.Trim(), "SHA1") ;
            if (txtPWD.Text.Trim() != hidPwd.Value)
            {
                dicParam.Add("PWD", System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(txtPWD.Text.Trim(), "SHA1"));
                hidPwd.Value = newPwd;
            }
            //}
            dicParam.Add("PortID", txtPortID.Text.Trim());
            dicParam.Add("RegDate", DateTime.Now.ToString());
            if (dropactID.Enabled)
            {
                dicParam.Add("actID", dropactID.SelectedValue);
            }
            dicParam.Add("RX", txtRX.Text.Trim());
            dicParam.Add("TX", txtTX.Text.Trim());
            dicParam.Add("isOnLine", "0");


            dicParam.Add("state", "S");


            dicParam.Add("content", txtcontent.Text.Trim());

            // 编辑
            if (!string.IsNullOrEmpty(Request.QueryString["action"]) && Request.QueryString["action"].ToLower() == "edit")
            {
                if (Utils.IsNumber(Request.QueryString["ID"]))
                {
                    Edit("userInfo", dicParam, "ID=" + Request.QueryString["ID"]);

                    if (Result > 0)
                    {
                        MsgContent = ShowMessage("恭喜您，更新成功！", MessageType.Success, false, true);
                        NoRefresh();
                    }
                    else
                    {
                        if (Result == -100)
                        {
                            MsgContent = ShowMessage("对不起，操作失败，程序参数异常。", MessageType.Error, false, true);
                        }
                        else
                        {
                            MsgContent = ShowMessage("对不起,操作失败，请重试。", MessageType.Error, false, true);
                        }
                    }
                }
            }
            else  // 新增
            {
                Insert("userInfo", dicParam);

                if (Result > 0)
                {
                    MsgContent = ShowMessage("恭喜您，添加成功！", MessageType.Success, false, true);
                    NoRefresh();
                }
                else
                {
                    MsgContent = ShowMessage("对不起,操作失败，请重试。", MessageType.Error, false, true);
                }
            }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["backUrlParam"]))
            {
                Response.Redirect("UserInfoList.aspx?" + Request.QueryString["backUrlParam"], false);
            }
            else
            {
                Response.Redirect("UserInfoList.aspx", false);
            }
        }
    }

}